package com.fjwt.gz.components.oss.service;

import cn.hutool.core.lang.UUID;
import com.fjwt.gz.components.oss.model.OssFileConfig;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.model.DBOSSConfig;
import com.fjwt.gz.core.service.ISysConfigService;
import com.fjwt.gz.core.utils.FileKit;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class OssFileService {

    @Value("${province.code}")
    private String provinceCode;


    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 统一校验, 获取文件的存储地址
     */
    private String commonCheckAndGetFilePath(String provinceCode, String bizType, String fileOriginalFilename, Long fileSize) {

        OssFileConfig ossFileConfig = OssFileConfig.getOssFileConfigByBizType(bizType);

        //1. 判断bizType 是否可用
        if (ossFileConfig == null) {
            throw new BizException("类型有误");
        }

        // 2. 判断文件是否支持
        String fileSuffix = FileKit.getFileSuffix(fileOriginalFilename, false);
        if (!ossFileConfig.isAllowFileSuffix(fileSuffix)) {
            throw new BizException("上传文件格式不支持！");
        }

        // 3. 判断文件大小是否超限
        if (!ossFileConfig.isMaxSizeLimit(fileSize)) {
            throw new BizException("上传大小请限制在[" + ossFileConfig.getMaxSize() / 1024 / 1024 + "M]以内！");
        }

        // 新文件地址 (xxx/xxx.jpg 格式)
        return provinceCode + "/" + bizType + "/" + UUID.fastUUID() + "." + fileSuffix;
    }


    /**
     * 后端java直接调用上传
     */
    public String singleFileUpload(MultipartFile file, String bizType) {

        // 文件存储路径
        String saveDirAndFileName = commonCheckAndGetFilePath(provinceCode, bizType, file.getOriginalFilename(), file.getSize());

        // 预览地址
        return getOssService().upload2PreviewUrl(OssFileConfig.getOssFileConfigByBizType(bizType).getOssSavePlaceEnum(), file, saveDirAndFileName);

    }


    private IOssService getOssService() {

        DBOSSConfig dbossConfig = sysConfigService.getOssConfig();
        return SpringBeansUtil.getBean(dbossConfig.getOssUseType() + "OssService", IOssService.class);

    }
}
